<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/7/25
 * Time: 16:36
 */

namespace app\common\model;

use think\Config;
use think\exception\HttpResponseException;
use think\Response;

/**
 * Class ApiResponse
 * @package app\common\model
 *
 * @property int code
 * @property string msg
 * @property mixed data
 * @property int total
 * @property int last_page
 */
class ApiResponse
{
    public $code;
    public $msg;
    public $data;

    public static function success($data = null, $total = null, $rows = 10, $lastPage = null) : ApiResponse {
        $re = new ApiResponse();
        $re->code = self::SUCCESS;
        $re->msg = 'success';
        $re->data = $data;
        if ($total) {
            $re->total = $total;
            if ($lastPage) $re->last_page = $lastPage;
            else $re->last_page = intval(ceil($total / $rows));
        }
        return $re;
    }

    public static function error(int $code, $msg = null) : ApiResponse {
        $re = new ApiResponse();
        $re->code = $code;
        $re->msg = $msg;

        $type = self::getResponseType();
        $response = Response::create($re, $type);
        throw new HttpResponseException($response);
    }

    /**
     * 获取当前的response 输出类型
     * @access protected
     * @return string
     */
    protected static function getResponseType()
    {
        return Config::get('default_return_type');
    }

    
    // 错误码详见文档
    
    const SUCCESS = 200;

    const ERR_INVALID_REQUEST = 400;
    const ERR_INVALID_APP = 401;
    const ERR_INVALID_URI = 404;
    const ERR_SERVER = 500;
    const ERR_CHAT_SERVER = 600;
    const ERR_CHAT_LACK_AVATAR = 601;
    const ERR_FORM_INVALID = 1010;
    const ERR_TOKEN_INVALID = 1011;
    const ERR_OPERATE_FAILED = 1012;
    const ERR_INVALID_INVITE_CODE = 1013;
    const ERR_NO_PURCHASE = 1014;
    const ERR_INVALID_PASSWORD = 1020;

    const ERR_NO_REAL_NAME_AUTH = 1030;
    const ERR_NOt_VIP = 1040;

    const ERR_EXISTS = 2002;
    const ERR_PARAM_INVALID = 2003;
    const ERR_RESOURCE_NON = 2404;

    const ERR_invited=3000;

    const EMPTY_PWD=4001;
    const ERR_PWD=4002;
}